package com.zx.练习题._2022面试题;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 请用 3 种不同原理实现线程安全且延迟加载（懒汉模式）的单例（Singleton）类；
 */
public class Demo5 {

    private static class Single1 {

        static volatile Single1 instance;

        private Single1() {
        }

        public static synchronized Single1 getInstance() {
            if (instance == null) {
                instance = new Single1();
            }
            return instance;
        }
    }

    private static class Single2 {

        static volatile Single2 instance;

        private Single2() {
        }

        public static Single2 getInstance() {
            if (instance == null) {
                synchronized (instance) {
                    if (instance == null) {
                        instance = new Single2();
                    }
                }
            }
            return instance;
        }
    }


    private static class Single3 {

        static volatile Single3 instance;
        static ReentrantLock lock;

        private Single3() {
        }

        public static Single3 getInstance() {
            if (instance == null) {
                lock.lock();
                try {
                    if (instance == null) {
                        instance = new Single3();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
            return instance;
        }
    }
}
